﻿using CS795.TravelAgency.Flight.Domain;
using CS795.TravelAgency.Flight.Domain.Entities;
using System;
using System.IdentityModel.Tokens;
using System.Linq;
using System.ServiceModel;
using System.Text;

namespace CS795.TravelAgency.Flight
{
    public class UserNamePasswordValidator : System.IdentityModel.Selectors.UserNamePasswordValidator
    {
        private FlightContext context = new FlightContext();

        public override void Validate(string userName, string password)
        {
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
            {
                throw new SecurityTokenException("Username and Password is required!");
            }

            User user = context.Users.Where(u => u.Name.ToLower().Equals(userName.ToLower())).SingleOrDefault();
            if (user == null)
            {
                throw new FaultException("Invalid username or password!");
            }

            string hashedPassword = EncryptPassword(user.Salt, password);
            if (hashedPassword != user.Password)
            {
                throw new FaultException("Invalid username or password!");
            }
        }

        private string EncryptPassword(string salt, string password)
        {
            string saltedPassword = salt + password;
            string hash = Convert.ToBase64String(System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(saltedPassword)));
            return hash;
        }
    }
}
